package com.mw.wmimobile.connection;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ConnectException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;

import android.os.AsyncTask;
import android.util.Log;

public class GetConnection extends AsyncTask<Void, Void, Boolean> {

	private static final String CONNECTION_ADRESS = "http://wmimobile.herokuapp.com/";
	
	private String method;
	private String myResult;
	private OnDownloadFinishedAction action;

	public GetConnection(String method, OnDownloadFinishedAction action) {
		Log.d("pracownicy", "odpalam connections");
		this.action = action;
		this.method = CONNECTION_ADRESS+method;
	}


	@Override
	protected Boolean doInBackground(Void... params) {

		Log.d("pracownicy", "do in backgroud");
		
		try {
			//tutaj jest tylko get, rozdzielic na kolejne?
			Log.d("pracownicy", method);
			//TUTAJ ZMIENIC W INNEJ KLASIE GET NA PUT

			HttpGet httpGet = new HttpGet(method);
			httpGet.setHeader("Accept", "application/json");
			httpGet.addHeader("Content-type", "application/json");
			
			HttpResponse response = Connector.httpclient.execute(httpGet);
			
			HttpEntity responseEntity = response.getEntity();
			
			
			
			InputStream stream = responseEntity.getContent();
			BufferedReader r = new BufferedReader(new InputStreamReader(stream));
			
			StringBuilder total = new StringBuilder();
			String line;
			while ((line = r.readLine()) != null) {
				total.append(line);
			}
			
			this.myResult = total.toString();
			
			Log.d("result", myResult);
			
			if(myResult==null){
				return false;
			}
			
			stream.close();
			responseEntity.consumeContent();
		
		} catch(IllegalStateException e){
			e.printStackTrace();
			return false;
		} catch(ConnectException e){
			e.printStackTrace();
			return false;
		} catch (ClientProtocolException e) {
			e.printStackTrace();
			return false;
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	protected void onPostExecute(Boolean result) {
		if (result) {
			action.onSuccess(myResult);
		}
		else {
			action.onFailure(myResult);
		}
	}


}
